package com.wkq.util

import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.ValueAnimator
import android.app.Activity
import android.content.Context
import android.content.ContextWrapper
import android.content.Intent
import android.graphics.Color
import android.os.Handler
import android.os.Looper
import android.view.MotionEvent
import android.view.View
import android.view.animation.DecelerateInterpolator
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2

/**
 *
 *@Author: wkq
 *
 *@Time: 2025/4/25 9:59
 *
 *@Desc:
 */

fun  TextView.textSafe(text: String?) {
    text?.let {
        this.text = it
    }
}

fun CharSequence?.replaceString(replace: String): String =
    this?.toString()?.replace(replace, "") ?: ""

fun <T> List<T>.getSafe(index: Int): T? {
    return if (index in indices) {
        this[index]
    } else {
        null
    }
}


/**
 * 安全判断 Context 关联的 Activity 是否处于无效状态（已销毁/即将销毁）
 * 同时处理 Context 为 null 或非 Activity 的情况
 * @return true：上下文无效（null/非Activity/Activity已销毁）；false：上下文有效（Activity正常存活）
 */
fun Context?.isFinishing(): Boolean {
    // 1. 处理 Context 为 null 的情况
    if (this == null) {
        return true
    }

    // 2. 从 Context 中获取最底层的 Activity（处理 ContextWrapper 包装的情况）
    val activity = this.unwrapActivity() ?: return true  // 非 Activity 上下文视为无效（如 Service/Application）

    // 3. 检查 Activity 是否处于销毁状态
    return activity.isFinishing || activity.isDestroyed
}

/**
 * 从 Context 中解析出底层的 Activity（处理 ContextWrapper 嵌套包装的情况）
 * @return 解析到的 Activity，若无法解析（非 Activity 类型）则返回 null
 */
private fun Context.unwrapActivity(): Activity? {
    var context = this
    // 循环解开 ContextWrapper 包装，直到找到 Activity 或无法继续解开
    while (context is ContextWrapper) {
        if (context is Activity) {
            return context
        }
        context = context.baseContext
    }
    return null  // 非 Activity 类型的 Context（如 Application/Service）
}



/**
 * 安全转换为 Int，支持默认值、范围限制、异常打印
 */
fun String?.toSafeInt(
    default: Int = 0,
    min: Int? = null,
    max: Int? = null,
    logError: Boolean = false
): Int {
    return try {
        val value = this?.toIntOrNull() ?: return default
        if ((min != null && value < min) || (max != null && value > max)) default else value
    } catch (e: Exception) {
        if (logError) e.printStackTrace()
        default
    }
}

/**
 * 安全转换为 Long，支持默认值、范围限制、异常打印
 */
fun String?.toSafeLong(
    default: Long = 0L,
    min: Long? = null,
    max: Long? = null,
    logError: Boolean = false
): Long {
    return try {
        val value = this?.toDoubleOrNull()?.toLong() ?: default ?: return default
        if ((min != null && value < min) || (max != null && value > max)) default else value
    } catch (e: Exception) {
        if (logError) e.printStackTrace()
        default
    }
}





// Context 扩展
fun Context.getSafeColor(colorResId: Int): Int = ContextCompat.getColor(this, colorResId)

fun Context.getSafeString(stringResId: Int, vararg args: Any): String =
    if (args.isEmpty()) getString(stringResId) else getString(stringResId, *args)

// Fragment 扩展（返回默认值，避免崩溃）
fun Fragment.getSafeColor(colorResId: Int, default: Int = Color.WHITE): Int =
    context?.getSafeColor(colorResId) ?: default

fun Fragment.getSafeString(stringResId: Int, vararg args: Any): String =
    context?.getSafeString(stringResId, *args) ?: ""




// 不带动画滑动到底部
fun RecyclerView.scrollBottom(lastPosition:Int){
    this.post { this.smoothScrollToPosition(lastPosition) }
}

// 带动画滑动到底部
fun RecyclerView.scrollAniBottom(lastPosition:Int){
    this.post { this.scrollToPosition(lastPosition) }
}


/**
* 展示View的扩展方法
 */

fun View.isShowOrGoneView(isShow: Boolean){
    this.visibility = if (isShow) View.VISIBLE else View.GONE
}

fun View.isShowOrInvisible(isShow: Boolean){
    this.visibility = if (isShow) View.VISIBLE else View.INVISIBLE
}

fun View.safeOnLongTouch(
    onStart: () -> Unit,
    onStop: () -> Unit
) {
    setOnTouchListener { _, event ->
        when (event.action) {
            MotionEvent.ACTION_DOWN -> {
                isPressed = true
                onStart()
                true
            }
            MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
                isPressed = false
                onStop()
                true
            }
            else -> false
        }
    }
}

/**
* 长按 抬起  点击
 */

fun View.setClickAndLongClickWithState(
    longPressTimeout: Long = 500L,
    onClick: () -> Unit,
    onLongClickStart: () -> Unit,
    onLongClickEnd: () -> Unit
) {
    var isLongPress = false
    val handler = Handler(Looper.getMainLooper())

    val longPressRunnable = Runnable {
        isLongPress = true
        isPressed = true  // 设置视图为“按下”状态
        onLongClickStart()
    }

    setOnTouchListener { _, event ->
        when (event.action) {
            MotionEvent.ACTION_DOWN -> {
                isLongPress = false
                handler.postDelayed(longPressRunnable, longPressTimeout)
                true
            }

            MotionEvent.ACTION_UP -> {
                handler.removeCallbacks(longPressRunnable)
                if (isLongPress) {
                    isPressed = false  // 释放按下状态
                    onLongClickEnd()
                } else {
                    onClick()
                }
                true
            }

            MotionEvent.ACTION_CANCEL -> {
                handler.removeCallbacks(longPressRunnable)
                if (isLongPress) {
                    isPressed = false
                    onLongClickEnd()
                }
                true
            }

            else -> false
        }
    }
}




fun ViewPager2.setScrollDuration( durationMs: Long = 500) {
    val pageWidth = this.width
    val startTime = System.currentTimeMillis()

    val animator = ValueAnimator.ofFloat(0f, 1f)
    animator.duration = durationMs
    animator.interpolator = DecelerateInterpolator()

    if (this.beginFakeDrag()) {
        animator.addUpdateListener {
            val elapsed = System.currentTimeMillis() - startTime
            val fraction = elapsed / durationMs.toFloat()
            val dragBy = pageWidth * fraction
            try {
                this.fakeDragBy(-dragBy)
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }

        animator.addListener(object : AnimatorListenerAdapter() {
            override fun onAnimationEnd(animation: Animator) {
                this@setScrollDuration.endFakeDrag()
            }
        })

        animator.start()
    }
}


